import json
import os
import time

from django.core import paginator
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from blog.models import Company, Interview, Resume, User, Job
from djangoProject2.settings import BASE_DIR


# Create your views here.


def createuser(request):
    return render(request, 'createuser.html')

# 用户登录界面
def login(request):
    return render(request, 'login.html')


# 主页
def index(request):
    name = request.session.get('name')
    company_queryset = Job.objects.all()
    # 创建 Paginator 对象，每页显示 2 个职位
    paginator = Paginator(company_queryset, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'name': name, 'contacts': contacts})


def main(request):
    name = request.session.get('name')
    return render(request, 'main.html', {'name': name})


#用户搜索
def company_search(request):
    name = request.session.get('name')
    type = request.GET.get('type')
    pay = request.GET.get('pay')
    experience = request.GET.get('experience')
    requirements = request.GET.get('requirements')
    job = request.POST.get('j')
    # 构建查询条件
    query = Q()
    if type:
        query &= Q(type=type)
    if pay:
        query &= Q(pay=pay)
    if experience:
        query &= Q(experience=experience)
    if requirements:
        query &= Q(requirements=requirements)
    if job:
        query &= Q(title = job)
        query &= Q(location = job)
    results = Job.objects.filter(query)
    paginator = Paginator(results, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'name': name, 'contacts': contacts})


# #创建用户判断
def createuser_pd(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        tel = request.POST.get('tel')
        name = request.POST.get('name')
        tel_1 = User.objects.filter(tel = tel)
        if tel_1:
            return JsonResponse({'msg': 'error'})
        else:
            User.objects.create(username = username,pwd = password,tel = tel,name=name)
            request.session['is_login'] = True
            user = User.objects.get(tel=tel)
            request.session['id'] = user.id
            request.session['username'] = user.username
            request.session['name'] = user.name
            company_queryset = Job.objects.all()
            # 创建 Paginator 对象，每页显示 2 个职位
            paginator = Paginator(company_queryset, 10)
            # 获取当前页码，默认为第一页
            page = request.GET.get('page', 1)
            try:
                # 获取当前页码的数据
                contacts = paginator.page(page)
            except PageNotAnInteger:
                # 如果页码不是整数，取第一页的数据
                contacts = paginator.page(1)
            except EmptyPage:
                # 如果页码超出范围，取最后一页的数据
                contacts = paginator.page(paginator.num_pages)
            return render(request, 'index.html', {'name': name, 'contacts': contacts})


#用户登录
def login_pd(request):
    if request.session.get('is_login', None):
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        lusername = request.POST.get('username')
        lpassword = request.POST.get('password')
        try:
            user = User.objects.get(username=lusername)
        except Exception:
            return HttpResponse("用户名不存在")

        if lpassword != user.pwd:
            return HttpResponse("用户名和密码不匹配")

        company_queryset = Job.objects.all().order_by('id')
        paginator = Paginator(company_queryset, 10)
        # 获取当前页码，默认为第一页
        page = request.GET.get('page', 1)
        try:
            # 获取当前页码的数据
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，取第一页的数据
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，取最后一页的数据
            contacts = paginator.page(paginator.num_pages)
        request.session['is_login'] = True
        request.session['username'] = user.username
        request.session['name'] = user.name
        request.session['id'] = user.id
        return render(request, 'index.html', {'name': user.name, 'contacts': contacts})


# # 招聘信息详情页面
def job_single(request):
    name = request.session.get('name')
    id = int(request.GET.get('id'))
    company_queryset = Job.objects.filter(id=id)
    return render(request, 'job-single.html', {'name': name, 'company_queryset': company_queryset})

# 简历投递成功按钮
def addresume(request):
    username = request.session.get('username')
    user = User.objects.get(username=username)
    usermsg = Resume.objects.filter(category_id=user.id)
    if usermsg.count() > 0:
        companyid = request.GET.get('id')
        companymsg = Job.objects.get(pk=companyid)
        user.job_set.add(companymsg)
        user.save()
        return JsonResponse({'msg': 'success'})
    else:
        return JsonResponse({'msg':'error'})


# 我的简历信息
def myresume(request):
    username = request.session.get('username')
    user = User.objects.get(username=username)
    resume = Resume.objects.filter(category_id=user.id)
    if resume.count()>0:
        resume2 = Resume.objects.get(category_id=user.id)
        return render(request, 'resume.html', {"user": user, "resume": resume2})
    else:
        return render(request, 'addresume.html', {"user": user, "resume": resume})


#上传简历
# def upload_document(request):
#     username = request.session.get('username')
#     user = User.objects.get(username=username)
#     resume = Resume.objects.get(category_id=user.id)
#     if request.method == "GET":
#         return render(request, "resume.html")
#     elif request.method == "POST":
#         files = request.FILES.get("file", None)
#         save_path = os.path.join(BASE_DIR, "file")
#         if not os.path.exists(save_path):
#             os.makedirs(save_path)
#         file_path = os.path.join(save_path, files.name)
#         with open(file_path, "wb") as fp:
#             for content in files.chunks():
#                 fp.write(content)
#         obj = Resume.objects.create(id=resume.id,file=files.name)
#         return HttpResponse(json.dumps({"id": obj.id, "name": files.name}, ensure_ascii=False),
#                             content_type="application/json,charset=utf-8")



# 添加简历信息
def addselfmsg(request):
    print("1")
    user_id = request.session.get('id')
    if request.method == 'GET':
        return render(request, 'addresume.html')
    if request.method == 'POST':
        age = request.POST.get('age')
        address = request.POST.get('address')
        Professional = request.POST.get('Professional')
        company_name1 = request.POST.get('company_name1')
        company_name2 = request.POST.get('company_name2')
        company_name3 = request.POST.get('company_name3')
        datetime1 = request.POST.get('datetime1')
        datetime2 = request.POST.get('datetime2')
        datetime3 = request.POST.get('datetime3')
        content1 = request.POST.get('content1')
        content2 = request.POST.get('content2')
        content3 = request.POST.get('content3')
        col_name = request.POST.get('col_name')
        col_time = request.POST.get('col_time')
        col_content = request.POST.get('col_content')
        max_deu = request.POST.get('max_deu')
        speciality = request.POST.get('speciality')
        Resume.objects.create(speciality=speciality,content2=content2,content3=content3,datetime1=datetime1,datetime2=datetime2,datetime3=datetime3,company_name1=company_name1,company_name2=company_name2,company_name3=company_name3,category_id=user_id,age=age,address=address,Professional=Professional,content1=content1,col_name=col_name,col_time=col_time,col_content=col_content,max_deu=max_deu)
        username = request.session.get('username')
        user = User.objects.get(username=username)
        resume2 = Resume.objects.get(category_id=user.id)
        return render(request, 'resume.html', {"user": user, "resume": resume2})
    else:
        return  JsonResponse({'msg': 'success'})

# # 投递信息查看
def message(request):
    name = request.session.get('name')
    id = request.session.get('id')
    interviewmsg = Interview.objects.filter(user_id=id)
    results = []
    if len(interviewmsg) >0:
        for i in interviewmsg:
            companymsg = Job.objects.get(id=i.job_id)
            if i.state_company != None:
                results.append(({'order_place':i.order_place,'id':i.id,'order_time':i.order_time,'title':companymsg.title,'type':companymsg.type,'pay':companymsg.pay,'cname':companymsg.name,'location':companymsg.location,'endtime':companymsg.endtime,'is_accept2': False,'is_accept': True}))
            else:
                results.append(({'order_place':i.order_place,'id':i.id,'order_time':i.order_time,'title':companymsg.title,'type':companymsg.type,'pay':companymsg.pay,'cname':companymsg.name,'location':companymsg.location,'endtime':companymsg.endtime, 'is_accept2': True,'is_accept':False}))

        paginator = Paginator(results, 10)
        # 获取当前页码，默认为第一页
        page = request.GET.get('page', 1)
        try:
            # 获取当前页码的数据
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，取第一页的数据
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，取最后一页的数据
            contacts = paginator.page(paginator.num_pages)
        return render(request, 'message.html', {'contacts': contacts,'name':name})
    else:
        return render(request, 'messageuser.html', {'msg':results,'name':name})



# # 用户是否接受面试
def accept(request):
    id = int(request.GET.get('id'))
    interviews = Interview.objects.get(id=id)
    interviews.state_user = 1
    interviews.save()
    return JsonResponse({'msg': 'success'})


#对我感兴趣
def interested(request):
    name = request.session['name']
    userid = request.session['id']
    request.session['is_login'] = True
    user = User.objects.get(id=userid)
    msg = user.company_set.all()
    results=[]
    if len(msg) >0:
        for i in msg:
            msg2= Company.objects.get(id=i.id)
            results.append(({'name': msg2.name,'caddress':msg2.caddress,'id':msg2.id}))
        paginator = Paginator(results, 10)
        # 获取当前页码，默认为第一页
        page = request.GET.get('page', 1)
        try:
            # 获取当前页码的数据
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，取第一页的数据
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，取最后一页的数据
            contacts = paginator.page(paginator.num_pages)
        return render(request, 'interestme.html',{'contacts':contacts,'name':name})
    else:
        return render(request, 'interestme2.html',{'name':name})




#对我感兴趣详情
def interestmedetails(request):
    name = request.session.get('name')
    id = int(request.GET.get('id'))
    company_queryset = Job.objects.filter(company_id=id)
    paginator = Paginator(company_queryset, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'interestdetail.html', {'name': name, 'contacts': contacts})






#----------------------------------------------------------公司端----------------------------------------------------------




def companylogin(request):
    return render(request, 'company_login.html')


# 公司首页

def company_main(request):
    name = request.session.get('cname')
    return render(request, 'company_main.html', {'name': name})

def showcreate(request):
    return render(request, 'company_creat.html')

def company_create(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        name = request.POST.get('name')
        address = request.POST.get('caddress')
        com = Company.objects.filter(name=name)
        if com !=None:
            cid = Company.objects.create(username=username, pwd=password, caddress=address, name=name).id
            request.session['cid'] = cid
            request.session['cname'] = name
            request.session['is_login'] = True
            user_queryset = Resume.objects.all().order_by('id')
            paginator = Paginator(user_queryset, 10)
            # 获取当前页码，默认为第一页
            page = request.GET.get('page', 1)
            try:
                # 获取当前页码的数据
                contacts = paginator.page(page)
            except PageNotAnInteger:
                # 如果页码不是整数，取第一页的数据
                contacts = paginator.page(1)
            except EmptyPage:
                # 如果页码超出范围，取最后一页的数据
                contacts = paginator.page(paginator.num_pages)
            return render(request, 'company_index.html',{'cname': name,'contacts':contacts,'is_login':True})
#主页
def company_index(request):
    cname = request.session.get('cname')
    user_queryset = Resume.objects.all().order_by('id')
    paginator = Paginator(user_queryset, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'company_index.html', {'cname': cname, 'contacts': contacts})


def user_search(request):
    cname = request.session['cname']
    user = request.POST.get('p')
    query = Q()
    if user:
        query &= Q(address=user)
        query &= Q(Professional=user)
        query &= Q(col_name=type)
        query &= Q(max_deu=type)

    results = User.objects.filter(query)
    paginator = Paginator(results, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'company_index.html', {'cname': cname, 'contacts': contacts})


    # #公司登录判断
def companylogin_pd(request):
    if request.method == 'POST':
        lusername = request.POST.get('username')
        lpassword = request.POST.get('password')
        try:
            company = Company.objects.get(username=lusername)
        except Exception:
            return HttpResponse("用户名不存在")

        if lpassword != company.pwd:
            return HttpResponse("用户名和密码不匹配")
        user_queryset = Resume.objects.all().order_by('id')
        request.session['is_login'] = True
        request.session['cname'] = company.name
        request.session['cid'] = company.id
        paginator = Paginator(user_queryset, 10)
        # 获取当前页码，默认为第一页
        page = request.GET.get('page', 1)
        try:
            # 获取当前页码的数据
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，取第一页的数据
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，取最后一页的数据
            contacts = paginator.page(paginator.num_pages)
        return render(request, 'company_index.html', {'cname': company.name, 'contacts': contacts})


#简历显示
def company_message(request):
    cname = request.session['cname']
    cid = request.session['cid']
    jobs = Job.objects.filter(company_id=cid)
    results = []  # 创建一个空列表来收集结果
    paginator = Paginator(results, 10)
    for k in jobs:
        interviewmsg = Interview.objects.filter(job_id=k.id)
        if interviewmsg.count() > 0:
            for i in interviewmsg:
                usermsgs = User.objects.get(id=i.user_id)
                usermsgs2 = Resume.objects.get(category_id=i.user_id)
                interviewmsg2 = Interview.objects.get(id=i.id)
                job = Job.objects.get(id=interviewmsg2.job_id)
                if i.order_time != None :
                    if i.state_user == 1:
                        results.append(({'job':job.title,'id':interviewmsg2.id,'order_time':interviewmsg2.order_time,'order_place':interviewmsg2.order_place,'Professional': usermsgs2.Professional,'name':usermsgs.name, 'age':usermsgs2.age,'address':usermsgs2.address,'col_name':usermsgs2.col_name,'exist':True,'exist4':True}))
                    else:
                        results.append(({'job':job.title,'id':interviewmsg2.id,'order_time':interviewmsg2.order_time,'order_place':interviewmsg2.order_place,'Professional': usermsgs2.Professional,'name':usermsgs.name, 'age':usermsgs2.age,'address':usermsgs2.address,'col_name':usermsgs2.col_name,'exist':True,'exist4':False}))

                else:
                    if i.state_user == 1:
                        results.append(({'job':job.title,'id':interviewmsg2.id,'order_time':interviewmsg2.order_time,'order_place':interviewmsg2.order_place,'Professional': usermsgs2.Professional,'name':usermsgs.name, 'age':usermsgs2.age,'address':usermsgs2.address,'col_name':usermsgs2.col_name,'exist':False,'exist4':True}))
                    else:
                        results.append(({'job':job.title,'id':interviewmsg2.id,'order_time':interviewmsg2.order_time,'order_place':interviewmsg2.order_place,'Professional': usermsgs2.Professional,'name':usermsgs.name, 'age':usermsgs2.age,'address':usermsgs2.address,'col_name':usermsgs2.col_name,'exist':False,'exist4':False}))

            # 获取当前页码，默认为第一页
            page = request.GET.get('page', 1)
            try:
                # 获取当前页码的数据
                contacts = paginator.page(page)
            except PageNotAnInteger:
                # 如果页码不是整数，取第一页的数据
                contacts = paginator.page(1)
            except EmptyPage:
                # 如果页码超出范围，取最后一页的数据
                contacts = paginator.page(paginator.num_pages)
            return render(request, 'companymessage.html', {'contacts': contacts, 'cname': cname})  # 返回所有结果
        else:
            return render(request, 'companymessageuser.html', {'cname': cname})




# #公司发布岗位
def showcompany_job(request):
    cid = request.session['cid']
    cname = request.session['cname']
    job = Job.objects.filter(company_id=cid).order_by("id")
    # 创建 Paginator 对象，每页显示 2 个职位
    paginator = Paginator(job, 10)
    # 获取当前页码，默认为第一页
    page = request.GET.get('page', 1)
    try:
        # 获取当前页码的数据
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，取第一页的数据
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，取最后一页的数据
        contacts = paginator.page(paginator.num_pages)

        # 将分页器和当前页码传递给模板
    return render(request, 'showcompany_job.html', {'contacts': contacts, 'page': page,'cname': cname})


# 公司发布岗位
def add_job(request):
    cname = request.session['cname']
    return render(request,'company_sendwork.html',{'cname':cname})
# #公司发布岗位
def company_sendworkaction(request):
    if request.method == 'POST':
        type = request.POST.get('type')
        pay = request.POST.get('pay')
        cid = request.session['cid']
        title = request.POST.get('title')
        location = request.POST.get('location')
        experience = request.POST.get('experience')
        description = request.POST.get('description')
        requirements = request.POST.get('requirements')
        num = request.POST.get('num')
        endtime = request.POST.get('endtime')
        name = request.POST.get('name')
        posted_date = time.strftime("%Y-%m-%d ",time.localtime())
        Job.objects.create(experience=experience,company_id=cid, title=title, location=location, description=description,pay=pay, type=type, requirements=requirements,num=num, endtime=endtime, name=name, posted_date=posted_date)
        return JsonResponse({"msg":"success"})


#企业查看简历详细信息
def company_single(request):
    cname = request.session.get('cname')
    id = int(request.GET.get('id'))
    user_queryset = Resume.objects.get(id=id)
    return render(request, 'companyjob-single.html', {'cname': cname, 'user_queryset': user_queryset})


#公司对用户感兴趣
def companysendmsg(request):
    companyid = request.session.get('cid')
    companymsg = Company.objects.get(pk=companyid)
    userid = request.GET.get('id')
    user = User.objects.get(pk=userid)
    user.company_set.add(companymsg)
    user.save()
    return JsonResponse({'msg': 'success'})

#
# #添加面试时间信息
def addinterviewmsg(request):
    order_time = request.POST.get('order_time')
    order_place = request.POST.get('order_place')
    interviewmsgid = request.POST.get('id')
    interviewmsg = Interview.objects.get(id=interviewmsgid)
    interviewmsg.order_time = order_time
    interviewmsg.order_place = order_place
    interviewmsg.state_company = 1
    interviewmsg.save()
    return JsonResponse({'msg': 'success'})





# 登录判断

#
#

# 退出登录
def logout(request):
    if not request.session.get('is_login', None):
        return redirect("/index/")

    request.session.flush()
    return redirect("/main/")
